package com.xcms.test;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class SampleServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
//        response.setHeader("Content-Type","text/html;utf-8");
//        response.setHeader("Refresh","3;url=index.jsp");
        String filename=request.getParameter("name");
        response.setHeader("content-disposition",
                "attachment;filename="+filename);
        //结合前面的IO知识
        //通过context对象获取绝对路径
        String contextPath=this.getServletContext().getRealPath("/");
//        System.out.println(contextPath);
        String pathfile=contextPath+"/"+filename;
        System.out.println(pathfile);
        FileInputStream in=new FileInputStream(new File(pathfile));
        ServletOutputStream out = response.getOutputStream();
        int count=-1;
        byte[] buff=new byte[1024*1024];
        while ((count=in.read(buff))!=-1){
            out.write(buff,0,count);
        }
        out.close();
        in.close();

    }
}
